package com.dj.uphome.web.controller;

import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.dj.common.web.controller.CoreCrudRestController;
import com.dj.common.web.exception.ErrorCodes;
import com.dj.common.web.exception.InvalidRequestException;
import com.dj.uphome.web.service.RestService;
import com.dj.uphome.web.shiro.ShiroUtil;
import com.dj.uphome.web.util.Const;

/**
 * 
 * 登录控制器
 *
 */
@Controller
public class LoginController extends CoreCrudRestController {
	
	
	@Autowired
	private RestService restService;

	@RequestMapping({"/to_login"})
	public ModelAndView admin() {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/admin/login");
		return mv;
	}

	/*****
	 * 用户登陆 正确：返回用户信息 错误:报异常
	 * @param vo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
	public ResponseEntity<JSON> login(@RequestParam String userName, @RequestParam String password) throws Exception {
		try {
			Map<String,Object> params = this.getParams();
			params.put("userName", userName);
			params.put("password", password);
			JSON json = restService.callPostRequest("/user/findByUserNameAndPassword", params);
			if (json != null) {
				Subject subject = SecurityUtils.getSubject();
				UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
				subject.login(token);
				ShiroUtil.getSession().setAttribute(Const.SESSION_USER, json);
			}
			return new ResponseEntity<>(json, HttpStatus.OK);
		} catch (AuthenticationException e) {
			e.printStackTrace();
			throw new InvalidRequestException(ErrorCodes.loginNameOrPasswdWrong);
		}
	}
	/**
	 * 退出登录 by jon
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/logout")
	public ModelAndView logout() throws Exception {
		ModelAndView mv = new ModelAndView();
		try {
			ShiroUtil.getSession().removeAttribute(Const.SESSION_USER);
			Subject subject = SecurityUtils.getSubject();
			// 身份认证
			if (subject.isAuthenticated()) {
				subject.logout();
			}
			mv.setViewName("login");
		} catch (Exception e) {
			mv.addObject("exception", e);
			mv.setViewName(defultError);
		}
		return mv;
	}
}
